function [output, status] = invsystem(command, newlineend)
% invsystem  - inverts the output argument order of system(...)
%
% FORMAT:           [output,status] = invsystem(command [,newlineend])
%
% Input fields:
%       command     command that is passed to system(...) call
%       newlineend  if given and == 1 leave trailing newlines in place
%
% See also system, unix, dos.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% enough arguments ?
if nargin < 1 || ...
   ~ischar(command)
    error( ...
        'BVQXtools:TooFewArguments',...
        'Too few arguments. Try ''help %s''.',...
        mfilename ...
    );
end

% do command with reversed arguments
try
    [status, output] = system(command(:)');

    % possibly remove any trailing newlines from output
    if nargin < 2 || ...
       ~isnumeric(newlineend) || ...
        isempty(newlineend) || ...
        isnan(newlineend(1)) || ...
        newlineend(1) ~= 1
        while ~isempty(output) && ...
            any(output(end) == char([10, 13]))
            output(end) = [];
        end
    end

% on error give status 1 and error message
catch
    status = 1;
    output = lasterr;
end
